<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\index\service;


use app\index\model\WechataQr;
use app\index\util\CreateNo;
use app\Oss;
use app\utils\Qrcode;
use think\facade\Db;

class QrcodeService
{

    private $userPath;
    private $commodityPath;
    private $verificationPath;

    private $baseIn;
    private $mallToken;
    private $mid;

    public function __construct()
    {
        global $baseIn, $mallToken, $mid;
        $this->baseIn = $baseIn;
        $this->mallToken = $mallToken;
        $this->mid = $mid;
        $this->userPath = "./storage/{$mid}/qrcode/agent/";
        $this->commodityPath = "./storage/{$mid}/qrcode/commodity/";
        $this->verificationPath = "./storage/{$mid}/qrcode/verification/";
    }


    public function qrcode($path, $data, $scene, $page)
    {
        $number = CreateNo::buildOrderNo(random_int(100000, 999999));
        $name = $this->baseIn . "_tongyong_" . hash('sha256', $number) . '.png';
        if ($this->baseIn == "wechata") {
            $qrcode = $this->checkWxa($this->userPath, $name, $scene, $page);
        } else {
            $text = request()->domain() . $path;
            if (empty(strspn($text, "?"))) {
                $text .= "?";
            }
            if (!empty($data)) {
                $data = json_decode($data, true);
                foreach ($data as $k => $v) {
                    $text .= $k . "=" . $v . "&";
                }
            }
            $text = trim($text, "&");
            $qrcode = $this->check($this->userPath, $name, $text);
        }

        return [HTTP_SUCCESS, $qrcode];
    }

    public function agent(int $agentId, $data = [])
    {

        $name = $this->baseIn . "_agent_" . hash('sha256', $agentId) . '.png';
        if ($this->baseIn == "wechata") {
            //$data['scene']['mallToken'] = $this->mallToken;
            $qrcode = $this->checkWxa($this->userPath, $name, $data['scene'], $data['page']);
        } else {
            $text = request()->domain() . "/index";
            $qrcode = $this->check($this->userPath, $name, $text);
        }

        return [HTTP_SUCCESS, $qrcode];
    }

    public function commodity(int $commodityId, ?int $agentId = 0, $data = [])
    {
        $name = $this->baseIn . "_commodity_" . hash('sha256', $commodityId . "_" . $agentId) . '.png';

        if ($this->baseIn == "wechata") {
            $qrcode = $this->checkWxa($this->commodityPath, $name, $data['scene'], $data['page']);
        } else {
            empty($agentId) ?
                $text = request()->domain() . "/h5/#/pages/detail/detail?id=$commodityId" :
                $text = request()->domain() . "/h5/#/pages/detail/detail?id=$commodityId&agent=$agentId";
            $qrcode = $this->check($this->commodityPath, $name, $text);
        }


        return [HTTP_SUCCESS, $qrcode];
    }

    public function verification(array $data, $scene = [])
    {
        array_multisort($data);
        $qrcodeData = (string)json_encode($data);
        $name = $this->baseIn . "_verification_" . hash('sha256', $qrcodeData) . '.png';
        $data['ids'] = implode(',', $data['ids']);
        if ($this->baseIn === "wechata") {
            global $mid, $user;
            $weaKey = uniqid('', true) . "_" . $user['id'];
            $wechataQrData = [
                'mall_id' => $mid,
                'wea_key' => $weaKey,
                'qr_data' => $data,
            ];
            WechataQr::create($wechataQrData);
            $page = isset($scene['page']) ? $scene['page'] : "";
            $qrcode = $this->checkWxa($this->verificationPath, $name, $weaKey, $page);
        } else {
            $text = url("/h5/#/pages/accept/accept", $data, false, true);
            $qrcode = $this->check($this->verificationPath, $name, $text);
        }

        return [HTTP_SUCCESS, $qrcode];
    }


    private function checkWxa($path, $name, $scene, $page)
    {

        $localPath = $path . $name;
        $qrcode = substr($localPath, 1);

        if (!is_file($localPath)) {
            $qrcodeManager = new Qrcode();
            $qrcodeManager->wxa($path, $name, $scene, $page);
        }

        return $qrcode;
    }

    private function check($path, $name, $text)
    {
        $localPath = $path . $name;
        $qrcode = substr($localPath, 1);

        if (!is_file($localPath)){
            Qrcode::create($path, $name, $text);
        }
        return $qrcode;
    }

    private function checkLocalOrOss()
    {
        $type = false;
        global $mid;
        $config = Db::table('jiecheng_configuration')
            ->where('type', 'oss')
            ->where('mall_id', $mid)
            ->value('configuration');
        if (empty($config)) {
            $saas_config = Db::table('jiecheng_saas_configuration')->where('type', 'oss')->value('configuration');
            $saas_js = json_decode($saas_config, true);
            if ($saas_js['is_open'] == 1) {
                $type = true;
            }
        } else {
            $js = json_decode($config, true);
            if ($js['oss_choice'] == 1) {
                $saas_config = Db::table('jiecheng_saas_configuration')->where('type', 'oss')->value('configuration');
                $saas_js = json_decode($saas_config, true);
                if ($saas_js['is_open'] == 1) {
                    $type = true;
                }
            } else {
                $type = true;
            }
        }
        return $type;
    }

}